<template>
  <el-dialog title="修改密码" :visible.sync="show" width="600px" :close-on-click-modal="false">
    <div>
      <el-form ref="ruleForm" :rules="rules" label-position="top" label-width="120px" :model="ruleForm">
        <el-form-item prop="old_password" label="旧密码">
          <el-input v-model="ruleForm.old_password" type="old_password" />
        </el-form-item>
        <el-form-item prop="password" label="新密码">
          <el-input v-model="ruleForm.password" type="password" />
        </el-form-item>
        <el-form-item prop="password2" label="确认新密码">
          <el-input v-model="ruleForm.password2" type="password" />
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="onAdd">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { mapGetters } from 'vuex'
import { http } from '@/api'
import { editPassword } from '@/api/user'

export default {
  name: 'PageAdd',
  data() {
    return {
      show: false,
      ruleForm: {
        password: '',
        password2: ''
      },
      rules: {
        old_password: [{ required: true, message: '不能为空' }],
        password: [{ required: true, message: '不能为空' }],
        password2: [{ required: true, message: '不能为空' }]
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  methods: {
    open() {
      this.ruleForm = {
        old_password: '',
        password: '',
        password2: ''
      }
      this.show = true
    },
    onAdd() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.ruleForm.password !== this.ruleForm.password2) return this.$message.error('两次输入密码不一致')
          editPassword({
            id: this.userInfo.id,
            old_password: this.ruleForm.old_password,
            new_password: this.ruleForm.password,
          }).then(res => {
            this.$message.success('修改成功')
            this.show = false
            this.$store.dispatch('user/logout').then(res => {
              this.$router.replace({
                path: '/login'
              })
            })
          })
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
